<template>
  <div class="watermark-img_wrapper">
    <!-- 返回上一页 - start -->
    <div class="go-back-box">
      <span class="back-btn" @click="goBack">
        <mds-icon type="line-arrow-left" />
        <span>返回上一页</span>
      </span>
      <mds-divider></mds-divider>
    </div>
    <!-- 返回上一页 - end -->
    <h3>图片合成</h3>
    <div class="app-list_wrapper">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="120px"
      >
        <!-- 主图片 -->
        <el-form-item label="主图片" prop="mainImgs">
          <el-upload
            action=""
            :multiple="true"
            list-type="picture-card"
            :on-change="onMainListChange"
            accept="image/jpeg,image/png,image/bmp"
            :auto-upload="false"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <!--从图片 -->
        <el-form-item label="从图片" prop="affiliateImg">
          <el-upload
            action=""
            list-type="picture-card"
            :on-change="onAffiliateListChange"
            accept="image/jpeg,image/png,image/bmp"
            :auto-upload="false"
            :limit="1"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <!-- 从属性 -->
        <template v-if="ruleForm.affiliateImg">
          <h5>从属性：</h5>
          <el-form-item label="width" prop="width">
            <el-input
              v-model="ruleForm.width"
              placeholder="number | string"
            ></el-input>
          </el-form-item>
          <el-form-item label="height" prop="height">
            <el-input
              v-model="ruleForm.height"
              placeholder="number | string"
            ></el-input>
          </el-form-item>
          <el-form-item label="x" prop="x">
            <el-input
              v-model="ruleForm.x"
              placeholder="eg. x: 250 / '250px' / '100%' / 'left:250' / 'center'"
            ></el-input>
          </el-form-item>
          <el-form-item label="y" prop="y">
            <el-input
              v-model="ruleForm.y"
              placeholder="eg. y: 250 / '250px' / '100%' / 'top:250' / 'center'"
            ></el-input>
          </el-form-item>
          <!-- <el-form-item label="scale" prop="scale">
            <el-input
              v-model="ruleForm.scale"
              placeholder="number | string"
            ></el-input>
          </el-form-item>
          <el-form-item label="rotate" prop="rotate">
            <el-input
              v-model="ruleForm.rotate"
              placeholder="number | string"
            ></el-input>
          </el-form-item> -->
        </template>
        <!-- 操作 -->
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')"
            >合成</el-button
          >
          <el-button @click="resetForm('ruleForm')">重置</el-button>
          <el-button v-if="finalImgs && finalImgs.length !== 0" @click="saveImgs()" style="margin-left: 64px">保存全部</el-button>
        </el-form-item>
      </el-form>
      <!-- 展示区域 -->
      <template v-if="finalImgs && finalImgs.length !== 0">
        <el-carousel :interval="4000" :type="finalImgs.length < 3 ? '' : 'card'" height="300px" class="preview-img_wrapper">
          <el-carousel-item v-for="item in finalImgs" :key="item">
            <img :src="item" alt="" />
          </el-carousel-item>
        </el-carousel>
      </template>
    </div>
  </div>
</template>

<script>
import image2canvas from "image-compose";
import { getImgRatio, fileToBase64, base64ByBlob, saveShareContent } from "../../../utils/helper";

export default {
  name: "watermark-img-page",
  data() {
    return {
      ruleForm: {
        mainImgs: [],
        affiliateImg: "",
        width: "0",
        height: "0",
        x: "0",
        y: "0",
        scale: "1",
        rotate: "1",
      },
      rules: {
        mainImgs: [
          {
            required: true,
            type: "array",
            message: "请选择主图片",
            trigger: "change",
          },
        ],
        affiliateImg: [
          {
            required: true,
            message: "请选择从图片",
            trigger: "change",
          },
        ],
        x: [
          {
            required: true,
            message: "eg. x: 250 / '250px' / '100%' / 'left:250' / 'center'",
            trigger: "change",
          },
        ],
        y: [
          {
            required: true,
            message: "eg. y: 250 / '250px' / '100%' / 'top:250' / 'center'",
            trigger: "change",
          },
        ],
        width: [
          {
            required: true,
            message: "number | string",
            trigger: "change",
          },
        ],
        height: [
          {
            required: true,
            message: "number | string",
            trigger: "change",
          },
        ],
        scale: [
          {
            required: true,
            message: "number | string",
            trigger: "change",
          },
        ],
        rotate: [
          {
            required: true,
            message: "number | string",
            trigger: "change",
          },
        ],
      },
      finalImgs: [],
      finalImgsName: [],
    };
  },
  created() {},
  methods: {
    saveImgs() {
      const { finalImgs, finalImgsName } = this
      if (finalImgs) {
        finalImgs.forEach((i, ind) => {
          saveShareContent(i, finalImgsName[ind] || '')
        })
      }
    },
    onMainListChange(file, list) {
      this.ruleForm.mainImgs = list;
    },
    async onAffiliateListChange(file, list) {
      const { width, height } = await getImgRatio(file.raw);
      this.ruleForm.affiliateImg = file;
      this.ruleForm.width = width;
      this.ruleForm.height = height;
    },
    async mergeImgs() {
      const self = this;
      this.finalImgs = [];
      this.finalImgsName = [];
      const gUrl = await this.getImagePath(this.ruleForm.affiliateImg.raw);
      self.ruleForm.mainImgs.forEach(async (i) => {
        const { width, height } = await getImgRatio(
          i.raw
        );
        const iUrl = await self.getImagePath(i.raw);
        const data = await image2canvas(
          {
            url: iUrl,
            width,
            height,
          },
          [
            {
              url: gUrl,
              width: self.ruleForm.width,
              height: self.ruleForm.height,
              sx: self.ruleForm.x,
              sy: self.ruleForm.y,
            },
          ]
        );
        base64ByBlob(data, (blob) => {
          self.finalImgsName.push(i.name);
          self.finalImgs.push(window.URL.createObjectURL(blob));
          self.$nextTick(() => {
            if (self.finalImgs.length === self.ruleForm.mainImgs.length) {
              const el = document.querySelector('.el-main')
              if (el) {
                el.scrollTop = '999999'
              }
            }
          })
        })
      });
    },
    getImagePath(file) {
      return new Promise((resolve) => {
        fileToBase64(file).then((base64) => {
          resolve(base64);
        });
      });
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log("可以提交");
          this.mergeImgs();
        } else {
          console.error("不能提交");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    goBack() {
      this.$router.replace("/process");
    },
  },
};
</script>

<style lang="scss" scoped>
.watermark-img_wrapper {
  color: #000;
  h3 {
    padding: 12px 0 20px 0;
    span {
      font-size: 14px;
    }
  }
  .preview-img_wrapper {
    .el-carousel__item {
      display: flex;
      justify-content: center;
      align-items: center;
      img {
        max-width: 100%;
        max-height: 100%;
      }
    }
  }
}
</style>
